package blue.web.thread;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class TaskExecutorConfig {

    //io 密集型
    @Bean("ioTaskExecutor")
    @Scope("prototype")
    public Executor ioTaskExecutor() {
        ThreadPoolTaskExecutor executor=newExecutor(200,200,2000,"ioTaskExecutor");
        System.out.println("new className=================");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
    //cpu 密集型
    @Bean("cpuTaskExecutor")
    @Scope("prototype")
    public Executor cpuTaskExecutor() {
        ThreadPoolTaskExecutor executor=newExecutor(16,16,2000,"cpuTaskExecutor");
        System.out.println("new className===================");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }

    private ThreadPoolTaskExecutor newExecutor(int coreSize,int maxSize,int queueSize,String namePrefix){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(coreSize);
        executor.setMaxPoolSize(maxSize);
        executor.setQueueCapacity(queueSize);
        executor.setKeepAliveSeconds(60);
        if(StringUtils.isBlank(namePrefix)){
            namePrefix="taskExecutor";
        }
        executor.setThreadNamePrefix(namePrefix);

        return executor;
    }

}
